from typing import Optional, Generator
from contextlib import contextmanager
import os

from sqlalchemy import types, create_engine
from sqlalchemy.orm import declarative_base, mapped_column, Mapped
from sqlalchemy.orm import sessionmaker, Session


Base = declarative_base()

class 虎码(Base):
    __tablename__ = '虎码'
    
    编号: Mapped[Optional[int]] = mapped_column(types.Integer, primary_key=True, unique=True, nullable=False)
    字符: Mapped[str] = mapped_column(types.String, unique=True, nullable=False)
    级别: Mapped[Optional[str]] = mapped_column(types.String, nullable=True)
    频数: Mapped[Optional[int]] = mapped_column(types.Integer, nullable=True)
    拆分: Mapped[Optional[str]] = mapped_column(types.String, nullable=True)
    全码: Mapped[Optional[str]] = mapped_column(types.String, nullable=True)
    一简: Mapped[Optional[str]] = mapped_column(types.String, nullable=True)
    二简: Mapped[Optional[str]] = mapped_column(types.String, nullable=True)
    三简: Mapped[Optional[str]] = mapped_column(types.String, nullable=True)
    容错: Mapped[Optional[str]] = mapped_column(types.String, nullable=True)
    备注: Mapped[Optional[str]] = mapped_column(types.String, nullable=True)



# 引擎 = create_engine('sqlite:///:memory:')
引擎 = create_engine('sqlite:///虎码.db')
Base.metadata.create_all(bind=引擎)

会话类 = sessionmaker(bind=引擎)

@contextmanager
def 获取会话() -> Generator[Session, None, None]:
    会话 = 会话类()
    try:
        yield 会话
        会话.commit()
    except Exception as e:
        会话.rollback()
        raise e
    finally:
        会话.close()